import threading
from selenium.webdriver.chrome.webdriver import WebDriver
from bdtime import tt, Time
from selenium.webdriver import ActionChains
from selenium import webdriver
import os
import re

with open('flag.txt', 'w+') as f:
    # 初始化时创建flag文件, 向内写入任意数据则break程序.
    pass

# if not os.path.exists('flag.txt'):
#     # 创建flag文件, 用来终止程序.
#     with open('flag.txt', 'w+') as f:
#         pass


def save_ls(ls):
    ss = ','.join([str(i) for i in ls])
    with open('cache.txt', 'w+') as f:
        f.write(ss)


def get_ls(fname='cache.txt'):
    if not os.path.exists(fname):
        return None

    with open(fname, 'r') as f:
        data = f.read()

    data = re.sub('#.*\n', '', data, re.M)
    l1 = data.split(',')
    ll = [int(i.strip()) for i in l1]
    return ll


t_confirm_threading = Time()


def confirm_threading(driver: WebDriver):
    """
    * 自动点击确认
    * 自动人脸识别(待完善)

    - 反反作弊模块
    """
    # driver: WebDriver = robot.driver
    xpath = "//button[@class='ant-btn ant-btn-primary']"

    while 1:
        if t_confirm_threading.now() < 10:
            continue

        try:
            print("--- 执行反检测 ---")
            elem = driver.find_element_by_xpath(xpath)
            elem.click()
            print("---~~~ 反检测成功 ~~~---")
        except:
            print('--- 没有发现检测模块')
            t_confirm_threading.sleep(5)

        t_confirm_threading.__init__()

        if get_flag():
            break


def get_flag():
    # 是否暂停的flag
    with open('flag.txt', 'r') as f:
        data = f.read()

    ret = False
    if data.strip():
        print('~~~ break! ~~~')
        ret = True
    return ret


def judge_text12(text1, text2):
    """
    * 判断text2 是否大于 text1

    :param text1: 最大时间
    :param text2: 当前时间
    """

    m1, s1 = text1.split(':')
    m2, s2 = text2.split(':')

    ret = 0
    if m1 < m2:
        ret = 1
    elif m1 == m2:
        if s1 <= s2:
            ret = 1

    return ret


class Robot:
    """
    刷课脚本
    """
    def __init__(self,
                 url='',        # 初始网页
                 driver=None,
                 username='',
                 password='',
                 ):
        if driver is None:
            self.driver = self.get_driver()
        else:
            self.driver = driver
        self.driver: WebDriver
        self.username = username
        self.password = password

    def confirm_threading(self):
        """
        运行反检测线程(自动点击"确认")
        """
        trd = threading.Thread(target=confirm_threading, args=(self.driver,))
        trd.start()

    def login(self):
        driver: WebDriver = self.driver
        driver.get_cookies()

        driver.get('https://www.bjjnts.cn/user/login')
        driver.find_element_by_id('login-hooks_username').send_keys(self.username)
        driver.find_element_by_id('login-hooks_password').send_keys(self.password)
        driver.find_element_by_css_selector("[class='ant-btn ant-btn-primary login_btn___3cgfH']").click()

    def get_driver(self):
        """
        初始化selenium
        """
        # 进入浏览器设置
        options = webdriver.ChromeOptions()
        # 设置中文
        options.add_argument('lang=zh_CN.UTF-8')

        options.add_argument("--mute-audio")    # 静音

        # 更换头部
        options.add_argument(
            'user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"')

        # options.add_argument("--user-data-dir=" + r'/Users/mac/Library/Application Support/Google/Chrome/')       # 使用默认chrome配置, 但版本必须正确

        options.add_argument('disable-infobars')     # 关闭"正在受到自动化软件控制"的提示

        # 创建浏览器对象
        driver = webdriver.Chrome(chrome_options=options)
        driver.set_window_position(y=50, x=10)
        driver.set_window_size(width=800, height=600, windowHandle='current')

        return driver

    def init_class(self):
        """
        初始化网页
        """
        pass

    def get_url_i(self, url_i=None):
        driver = self.driver

        print('--- get_url_i:', url_i)

        driver.get(url_i)

    def _start_video(self):
        driver = self.driver
        driver.find_element_by_class_name('outter').click()

    def _mouse_hover(self):
        # 鼠标悬停
        driver = self.driver

        xpath = "//video"
        hover_element = driver.find_element_by_xpath(xpath)
        ActionChains(driver).move_to_element(hover_element).perform()

    def _get_elem_text(self):
        # 获取文本, 判断视频是否已播放完毕
        driver = self.driver

        xpath1 = "//div[@class='prism-time-display']/span[@class='duration']"
        xpath2 = "//div[@class='prism-time-display']/span[@class='current-time']"
        elem1 = driver.find_element_by_xpath(xpath1)
        elem2 = driver.find_element_by_xpath(xpath2)
        # print(elem1.text, '---', elem2.text)
        return elem1.text, elem2.text

    def is_end(self):
        """
        判断当前播放的video是否结束
        """
        driver = self.driver

        try:
            text1, text2 = self._get_elem_text()
            ret = judge_text12(text1, text2)
            return ret
        except:
            print('运行_get_elem_text失败!')

        xpath = "//button[@class='next_button___YGZWZ']"
        try:
            elem = driver.find_element_by_xpath(xpath)

            if elem:
                return 1
            else:
                return 0
        except:
            self._mouse_hover()
            return 0

    def get_next_unit(self):
        driver = self.driver

        xpath = "//button[@class='next_button___YGZWZ']"
        elem = driver.find_element_by_xpath(xpath)
        elem.click()

    def sleep(self, t=10):
        tt.sleep(min(t/2, 2))
        self.driver.implicitly_wait(t)

    def brush_one(self, url_i='', auto_next=False):
        """
        开刷
        """
        # self._get_url_i(url_i)
        self.sleep(10)
        self._start_video()
        self._mouse_hover()

        print('~~ 开始刷课~~', tt.now(1))
        tt.__init__()
        while 1:
            self.sleep(10)
            if get_flag():
                break

            if self.is_end():
                if auto_next:
                    try:
                        self.get_next_unit()
                    except:
                        print('!! 可能是已经播放过的视频?')
                        base_url, current_unit_i = url_i.rsplit('=', 1)
                        next_unit_i = eval(current_unit_i) + 1
                        next_url = base_url + '=' + str(next_unit_i)
                        # self.get_url_i(next_url)
                        print('~~~--- get_url_i:', next_url)
                return 1
            else:
                print('~~~~', tt.now(1), '   ---   ', url_i)

    def close(self):
        self.driver.close()

    def run(self):
        robot = self
        pass


if __name__ == '__main__':
    robot = Robot()
    # robot = Robot(driver=driver)
    # url_i = 'https://www.bjjnts.cn/study/video?class_id=26983&course_id=2483&unit_id=34930'
    # robot.get_url_i(url_i=url_i)
    # # robot.driver.implicitly_wait(1)
    # robot._start_video()
    # robot._mouse_hover()
    # robot.is_end()
    #
    # url_i = 'https://www.bjjnts.cn/study/video?course_id=2483&unit_id=34931&class_id=26983'
    # robot.brush_one(url_i)
    #
    # driver = 1
    # # driver.1
    # 'next_button___YGZWZ'

    pass
